package logic

import (
	"common/dao/model"
	"common/modelrsa"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"
	"time"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.UserLoginReq) (resp *types.Emp, err error) {
	// todo: add your logic here and delete this line
	var (
		user = model.SysUser{}
	)
	db := l.svcCtx.DB.Table(model.TableNameSysUser)
	err = db.Transaction(func(tx *gorm.DB) error {
		err := tx.Where("account = ?", req.Username).Where("is_del = ?", 0).Find(&user).Error
		if err != nil {
			return err
		}
		if user.UUID != "" {
			return errors.New("该用户已注册！")
		}
		decrypt, err := modelrsa.Decrypt(req.PassWord)
		if err != nil {
			return err
		}
		password, err := modelrsa.HashPassword(decrypt)
		if err != nil {
			return err
		}
		user2 := model.SysUser{}
		user2.UUID = utils.GetUuid()
		user2.Account = req.Username
		user2.Password = password
		t := time.Now()
		user2.CreateTime = &t
		if err := tx.Create(&user2).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return
}
